/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.meuevento.business.event;

import com.meuevento.business.general.CrudService;
import com.meuevento.util.ErrorManager;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rmpestano
 */
@Stateless
public class EventService {

    @EJB CrudService<Event> crudService;

    @PersistenceContext EntityManager em;

    public List<Event> listEvents(){
        System.out.println("Listing all eventss...");
        List<Event> events = crudService.findAll(Event.class);
        for (Event event : events) {
            System.out.println(event.toString());
        }
        return events;
    }

    public Event findById(long id){
        HashMap<Object,Long> parameters = new HashMap<Object, Long>();
        parameters.put("id", id);
        List<Event> events = crudService.findWithNamedQuery(Event.FIND_BY_ID,parameters);
        for (Event event : events) {
            System.out.println(event.getName());
        }
        return events.get(0);
    }
    public Event findByName(String name){
        HashMap<Object,String> parameters = new HashMap<Object, String>();
        parameters.put("name", name);
        List<Event> events = crudService.findWithNamedQuery(Event.FIND_BY_NAME,parameters);
        for (Event event : events) {
            System.out.println(event.getName());
        }
        return events.get(0);
    }

   public Event insert(Event event){
       try {
           crudService.create(event);
       } catch (Exception ex) {
           ErrorManager.generateError(ex.getMessage(), "problema ao inserir evento:" + event.getName());
           ex.printStackTrace();
           return null;
       }
       return event;
    }

   public void remove(Event event) throws Exception{

         crudService.delete(Event.class, event.getEventId());

   }
}
